package com.efeichong.common.config.flowLimit;

import com.efeichong.annotation.FlowLimit;
import com.efeichong.common.exception.CustomException;
import lombok.SneakyThrows;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author lxk
 * @date 2022/8/21
 * @description 频率限制切面处理
 */
@Component
@Aspect
public class FlowLimitAspect {

    @Autowired
    private SlideWindowFlowLimitHandler slideWindowFlowLimitHandler;

    @SneakyThrows
    @Before("execution(* com..controller..*.*(..)) && @annotation(fl)")
    public void flowLimit(JoinPoint joinPoint, FlowLimit fl) {
        String key = joinPoint.getSignature().toString();
        boolean flow = slideWindowFlowLimitHandler.flow(key, fl.value());
        if (!flow) {
            throw new CustomException("当前请求太过频繁,请稍后操作");
        }
    }

}
